package com.stgy.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stgy.lease.common.config.MinioConfig;
import com.stgy.lease.common.exception.StgyException;
import com.stgy.lease.common.result.ResultCodeEnum;
import com.stgy.lease.model.domain.GraphInfo;
import com.stgy.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

/**
 * ClassName:FileServiceImpl
 * Package:com.example.demo01minio.service.impl
 * Description:
 *
 * @Author:helei
 * @Create:2024/8/27 - 9:40
 */
//@EnableConfigurationProperties(MinioProperties.class)
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient client;

    @Override
    public String upload(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //1、获取文件信息：文件校验，文件的名称
        InputStream is = file.getInputStream();
        if (is.available() == 0) {
            throw new StgyException(ResultCodeEnum.FILE_EXISTS_ERROR);
        }
        String contentType = file.getContentType().toLowerCase();
        //获取文件名称
        String filename = file.getOriginalFilename();
        String last = filename.substring(filename.lastIndexOf("."));

        if (!MinioConfig.MEDIA_TYPES
                .contains(last)) {
            throw new StgyException(ResultCodeEnum.FILE_EXISTS_ERROR);
        }
        //2、拼接保存到桶内的文件路径和文件名称
        String objectName = MinioConfig.MODULE + "/" +//文件名称
                new DateTime().toString("yyyy/MM/dd/") + //时间日期路径
                System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 6) +//文件名称
                filename.substring(filename.lastIndexOf("."));//.jpg
        client.putObject(PutObjectArgs.builder()
                .bucket(MinioConfig.BUCKET)
                .stream(is, is.available(), -1)
                //要写入到桶内的文件路径&文件名称
                .object(objectName)
                //设置文件的contentType 可以通过spring-web包MediaType来获取文件类型
//                .contentType("image/jpg")
                .contentType(contentType.toString())
                .build());
        //3、拼接上传成功的文件路径
        //http://192.168.144.128:9000/demo02/test/2024/08/27/1724722446068_dea6a5.jpg
//        String imgUrl = "http://192.168.144.128:9000/stgy/" + objectName;
        String imgUrl = MinioConfig.ENDPOINT + "/" + MinioConfig.BUCKET + "/" + objectName;
        return imgUrl;
    }

    @Override
    public String delete(String path) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//        http://192.168.144.128:9000/stgy/image.jpg

        int i = (MinioConfig.ENDPOINT + "/" + MinioConfig.BUCKET + "/").length();
        String url = path.substring(i);
        client.removeObject(RemoveObjectArgs.builder()
                .bucket(MinioConfig.BUCKET)
                .object(url).build());
        return null;
    }

    @Async //异步执行：spring通过aop开子线程执行
    //线程资源需要我们人为控制：线程数量
    @Override
    public void batchDelete(List<GraphInfo> graphInfos, Long id) {
        for (GraphInfo graphInfo : graphInfos) {
            try {
                this.delete(graphInfo.getUrl());
            } catch (Exception e) {
                log.error("stgy-roominfo-图片删除失败：url:{},roomId:{}",
                        graphInfo.getUrl(), id);
            }
        }
    }
}